package longrise.phone.com.bjjt_henan.bindinginformation;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.LFView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.FileUtils;
import com.longrise.bjjt.util.UiUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.File;

import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.CheckCard;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.compensate.HeNanSurfaceViewCameraActivity;

/**
 * 绑定、修改驾驶证界面
 */
public class BindDriveCardView extends LFView implements View.OnClickListener,
        MainActivity.OnActivityReturnBitmap {
    private Context context = null;
    private View view = null;
    private TextView titleTV;
    private TextView infoTV;
    private EditText nameET;
    private EditText identityNumET;
    private EditText fileNumET;
    private ImageView driveCardIV;//驾驶证图片
    private Button confirmBtn;

    private EntityBean bean;//数据参数
    private String imageStr;//驾驶证图片的字符流
    private BaseApplication application;
    private String realName;
    private Dialog processDialog;

    public BindDriveCardView(Context c, EntityBean bean) {
        super(c);
        this.context = c;
        this.bean = bean;
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {

    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
        setData();
    }

    private void initView() {
        view = View.inflate(context, R.layout.view_binddrivecard, null);
        //标题栏
        titleTV = (TextView) view.findViewById(R.id.tv_title);
        view.findViewById(R.id.hn_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnDestroy();
                closeForm();
            }
        });
        infoTV = (TextView) view.findViewById(R.id.bcard_tv_info);
        nameET = (EditText) view.findViewById(R.id.bcard_ev_name);
        identityNumET = (EditText) view.findViewById(R.id.bcard_ev_identitynum);
        fileNumET = (EditText) view.findViewById(R.id.bcard_ev_filenum);
        driveCardIV = (ImageView) view.findViewById(R.id.bcard_iv_drivecard);
        confirmBtn = (Button) view.findViewById(R.id.bcard_btn_confirm);

        application = (BaseApplication) context.getApplicationContext();
    }

    private void regEvent(boolean b) {
        if (null != driveCardIV) {
            driveCardIV.setOnClickListener(b ? this : null);
        }
        if (null != confirmBtn) {
            confirmBtn.setOnClickListener(b ? this : null);
        }
    }

    public void setData() {
        if (null == bean) {//绑定操作
            titleTV.setText("绑定驾驶证");
//            infoTV.setText("请输入驾驶证信息");
            confirmBtn.setText("绑定");
        } else {
            titleTV.setText("修改驾驶证");
//            infoTV.setText("请修改驾驶证信息");
            confirmBtn.setText("确认修改");
            //姓名
            String name = bean.getString("carownername");
            if (!TextUtils.isEmpty(name)) {
                nameET.setText(name);
            }
            //身份证号
            String identity = bean.getString("cardno");
            if (!TextUtils.isEmpty(identity)) {
                identityNumET.setText(identity);
            }
            //档案编号
            String fileno = bean.getString("driverfileno");
            if (!TextUtils.isEmpty(fileno)) {
                fileNumET.setText(fileno);
            }
            //驾驶证照片
            String pic = bean.getString("drivernoimg");
            if (!TextUtils.isEmpty(pic)) {
                ImageLoader.getInstance().displayImage(pic, driveCardIV, CommontUtils.getOptions());
                imageStr = pic;//网络图片则保存图片路径
            }
        }
    }

    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.bcard_iv_drivecard://拍摄驾驶证
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putInt("backGroundResourceId", R.mipmap.jsz_4);
                    intent.putExtras(bundle);
                    intent.setClass(context, HeNanSurfaceViewCameraActivity.class);
                    ((Activity) context).startActivityForResult(intent, 99);
                    break;
                case R.id.bcard_btn_confirm://确定
                    confirmModify();
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 绑定或确认修改
     */
    private void confirmModify() throws Exception {
        if (TextUtils.isEmpty(imageStr)) {
            UiUtil.showToast(context, "请拍摄驾驶证照片");
            return;
        }
        realName = nameET.getText().toString().trim();
        if (!CommontUtils.isChinaName(realName)) {
            UiUtil.showToast(context, "请输入长度为2-16位的中文姓名");
            return;
        }
        String identityNum = identityNumET.getText().toString().trim();
        if (!CheckCard.IDCardValidate(identityNum)) {
            UiUtil.showToast(context, "请输入正确的身份证号");
            return;
        }
        String fileNum = fileNumET.getText().toString().trim();
        if (TextUtils.isEmpty(fileNum)) {
            UiUtil.showToast(context, "请输入档案编号");
            return;
        }
        String userflag = application.getKckpName();
        String token = application.getToken();
        DialogUtils.showDialog(context);
        if (null == bean) {//绑定
            ApiImpI.getInstance(application).addDriverInfo(userflag, token, realName, identityNum,
                    fileNum, imageStr, callBack);
        } else {//修改
            String cardId = bean.getString("id");
            ApiImpI.getInstance(application).modifyDriverinfo(cardId, userflag, identityNum,
                    realName, fileNum, token, imageStr, callBack);
        }
    }

    private ApiImpI.RequestCallBack callBack = new ApiImpI.RequestCallBack() {
        @Override
        public void onError(String error) {
            DialogUtils.closeDialog();
            if (!TextUtils.isEmpty(error)) {
                UiUtil.showToast(getContext(), error);
            }
        }

        @Override
        public void onSuccess(Object result) {
            DialogUtils.closeDialog();
            EntityBean bean = (EntityBean) result;
            String redes = bean.getString("redes");
            if (!TextUtils.isEmpty(redes)) {
                UiUtil.showToast(context, redes);
            }
            String restate = bean.getString("restate");
            if (TextUtils.equals("1", restate)) {
                //缓存数据
                application.getLoginInfo().getBean("userinfo").set("name", realName);
                LSMsgCall(99, "bindinfo");
                OnDestroy();
                closeForm();
            }
        }
    };

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        view = null;
        regEvent(false);
        DialogUtils.destroyDialog();
    }

    @Override
    public void activityReturnBitmap(int requestCode, int resultCode, Intent data) {
        if (requestCode == 99 && resultCode == HeNanSurfaceViewCameraActivity.RESULT_OK) {
            final String path = data.getStringExtra("image");
            if (TextUtils.isEmpty(path)) {
                UiUtil.showToast(context, "拍照图片有误，请重新拍照！");
                return;
            }
            String imgpath = "file:///" + path;
            ImageLoader.getInstance().displayImage(imgpath, driveCardIV, CommontUtils.getOptions(),
                    new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String s, View view) {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {

                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                            imageStr = FileUtils.File2byte(new File(path), true);
                            processDialog = UiUtil.showProcessDialog(context, "正在识别...");
                            ApiImpI.getInstance(application).getOcrInfo(imageStr, "5", callBack2);
                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {

                        }
                    });
        }
    }

    private ApiImpI.RequestCallBack callBack2 = new ApiImpI.RequestCallBack() {
        @Override
        public void onError(String error) {
            if (null != processDialog) {
                if (processDialog.isShowing()) {
                    processDialog.dismiss();
                }
            }
            UiUtil.showToast(context, "图像识别失败，请重新拍照或者手动填写");
        }

        @Override
        public void onSuccess(Object result) {
            try {
                if (null != processDialog) {
                    if (processDialog.isShowing()) {
                        processDialog.dismiss();
                    }
                }
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                if ("1".equals(restate)) {
                    //图像识别成功，将内容填充到界面
                    EntityBean dataBean = bean.getBean("data");
                    if (null != dataBean) {
                        String name = dataBean.getString("name");//姓名
                        String idCartd = dataBean.getString("cardno");//身份证号
                        if (CommontUtils.isChinaName(name)) {
                            nameET.setText(name);
                        }
                        if (CheckCard.IDCardValidate(idCartd)) {
                            identityNumET.setText(idCartd);
                        }
                        return;
                    }
                }
                String redes = bean.getString("redes");
                UiUtil.showToast(context, redes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}